package com.sgb.kjwl.view.ui.activity.self.publish;

import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.graphics.Color;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.PopupWindow;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPublicMyPriceBinding;
import com.sgb.kjwl.model.entity.user.PublicMyPriceListEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseQuedPriceEvent;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.leaseAsk.AskLeaseMyPriceDetailActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.PublicMyPriceListAdapter;
import com.sgb.kjwl.view.widget.lease.LeaseAskMapPopWindow;
import com.sgb.kjwl.viewmodel.machine.PublicMyPriceListModel;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 租赁-我的报价/客户报价
 */
public class PublicMyPriceListActivity extends AppActivity {

    private ActivityPublicMyPriceBinding binding;
//    private String[] titles = {"机械求租", "设备求租", "车辆求租", "房产求租","土地求租"};

//    private String[] titles = {"全部", "已报价", "已接受", "已忽略"};//全部=""、已报价="0"、已接受="1"、已忽略="2"
//    private ArrayList<Fragment> mFragments;

    private PublicMyPriceListModel viewModel;
    private PublicMyPriceListAdapter adapter;

    private LeaseAskMapPopWindow classPopWindow;
    private LeaseAskMapPopWindow typePopWindow;
    private List<PickSelectEntity> classDatas;
    private List<PickSelectEntity> statusDatas;

    private String isAcceptQuote = "";//处理状态 （全部=""，0待接受，1已接受，已忽略=2，3已取消）
    private String categoryType = "";//求租类型
    private String titleOrCompanyName = "";//业务名称或客户名称
    private String titleOrDemandCompanyName = "";//业务名称或需求方名称
    private String type = "0";//0我的报价 1客户报价
    private boolean isLoadMore = false;//是否加载更多

    /**
     * @param context
     * @param type    0：我的报价，1：客户报价
     */
    public static void start(Context context, String type) {
        Intent intent = new Intent();
        intent.putExtra("type", type);
        intent.setClass(context, PublicMyPriceListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PublicMyPriceListActivity.this, R.layout.activity_public_my_price);
        viewModel = new ViewModelProvider(this).get(PublicMyPriceListModel.class);
        binding.topLayout.titleView.setText("我的报价");
        binding.topLayout.ivBack.setVisibility(View.VISIBLE);
        binding.topLayout.ivBack.setOnClickListener(view -> finish());
        binding.tvSearch.setOnClickListener(v -> {
            loadData(false);
        });
        binding.tvSearchDelete.setOnClickListener(v -> binding.editSearch.setText(""));
        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.editSearch.getText().toString().trim())) {
                        MToast.showToast(PublicMyPriceListActivity.this, "请输入搜索内容");
                        return true;
                    } else {
                        loadData(false);
                    }
                }
                return false;
            }
        });
        binding.editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.editSearch.getText())) {
                    binding.tvSearchDelete.setVisibility(View.VISIBLE);
                } else {
                    binding.tvSearchDelete.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    protected void init() {
        type = getIntent().getStringExtra("type");
        if ("1".equals(type)) {
            binding.topLayout.titleView.setText("客户报价");
            binding.editSearch.setHint("请输入业务名称或客户名称");
        } else {
            binding.topLayout.titleView.setText("我的报价");
            binding.editSearch.setHint("请输入业务名称或需求方名称");
        }
        initAdapter();
        receiverLiveData();
        initPopWindow();
        initData();
        loadData(false);
    }

    private void receiverLiveData() {
        viewModel.showListLiveData.observe(this, data -> {
            List<PublicMyPriceListEntity> list = data.getDataList();
            if (list == null || list.size() == 0) {
                list = new ArrayList<>();
            }
            showList(list);
        });
        viewModel.showStateLiveData.observe(this, data -> {
            if (!TextUtils.isEmpty(data)) {
                MToast.showToast(getActivity(), data);
            }
            loadData(false);
        });
        viewModel.showMyUrlLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String url) {
                WebViewX5HostActivity.start(PublicMyPriceListActivity.this, url);
            }
        });
        viewModel.showUrlLiveData.observe(this, new Observer<String[]>() {
            @Override
            public void onChanged(String[] strings) {
                //categoryType为详情分享使用，下标不一致需加1
                WebViewX5HostActivity.start(PublicMyPriceListActivity.this, strings[0], strings[1], "asklease", strings[2]);
            }
        });
    }

    private void initAdapter() {
        binding.classLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        if (adapter == null) {
            adapter = new PublicMyPriceListAdapter(getActivity(), null, type);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.rlvView.setLayoutManager(layoutManager);
        binding.rlvView.setAdapter(adapter);
        binding.rlvView.setLoadingMoreEnabled(true);
        binding.rlvView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });

        adapter.setonBtnClick(new PublicMyPriceListAdapter.onBtnClickListener() {
            @Override
            public void onChangePriceClick(PublicMyPriceListEntity entity, int position) {
                //接受报价
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("提示")
                        .setMsg("确定接受该报价吗？确定后报价状态变成已接受")
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                viewModel.acceptPrice(entity.getRentalSeekId(), entity.getId(), entity.getCategoryType());
                            }

                            @Override
                            public void onLeftClick() {
                            }
                        }).show();

            }

            @Override
            public void onCancelClick(PublicMyPriceListEntity entity, int position) {
                //取消报价
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("提示")
                        .setMsg("确定取消该报价吗？确定后报价状态变成已取消")
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                viewModel.cancelPrice(entity.getId());
                            }

                            @Override
                            public void onLeftClick() {
                            }
                        }).show();

            }

            @Override
            public void onViewDetailsClick(PublicMyPriceListEntity entity, int position) {
                //查看需求-H5
                if ("1".equals(entity.getDemandStatus())&&!"1".equals(entity.getIsAcceptQuote())) {
                    MToast.showToast(getActivity(), "该需求已被发布者删除");
                    return;
                }
                if ("1".equals(type)) {
                    viewModel.getMyH5Url(entity.getCategoryType(), entity.getRentalSeekId());
                } else {
                    viewModel.getH5Url(entity.getCategoryType(), entity.getRentalSeekId());
                }

            }

            @Override
            public void onItemClick(PublicMyPriceListEntity entity, int position) {
                //查看报价详情
                AskLeaseMyPriceDetailActivity.start(PublicMyPriceListActivity.this, entity, type);
            }

        });

    }

    private void initPopWindow() {
        classPopWindow = new LeaseAskMapPopWindow(getActivity());
//        classPopWindow.setBgView();
        classPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                categoryType = ((PickSelectEntity) type).getNo();
                binding.tvClass.setText(((PickSelectEntity) type).getProjectscale());
                binding.tvClass.setTextColor(Color.parseColor("#EF4033"));
                loadData(false);
            }
        });
        classPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.classArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

        typePopWindow = new LeaseAskMapPopWindow(getActivity());
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                isAcceptQuote = ((PickSelectEntity) type).getNo();
                binding.tvType.setText(((PickSelectEntity) type).getProjectscale());
                binding.tvType.setTextColor(Color.parseColor("#EF4033"));
                loadData(false);
            }
        });
        typePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.typeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
    }

    private void initData() {
        classDatas = new ArrayList<>();
        classDatas.add(new PickSelectEntity("", "不限"));
        classDatas.add(new PickSelectEntity("0", "机械求租"));
        classDatas.add(new PickSelectEntity("1", "设备求租"));
        classDatas.add(new PickSelectEntity("2", "车辆求租"));
        classDatas.add(new PickSelectEntity("3", "房产求租"));
        classDatas.add(new PickSelectEntity("4", "土地求租"));
        classDatas.add(new PickSelectEntity("5", "工厂求租"));
        classDatas.add(new PickSelectEntity("6", "农机求租"));
        //处理状态 处理状态 （全部=""，0待接受，1已接受，已忽略=2，3已取消）
        statusDatas = new ArrayList<>();
        statusDatas.add(new PickSelectEntity("", "不限"));
        statusDatas.add(new PickSelectEntity("0", "待接受"));
        statusDatas.add(new PickSelectEntity("1", "已接受"));
        statusDatas.add(new PickSelectEntity("3", "已取消"));
    }

    public void loadData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        if ("1".equals(type)) {
            titleOrCompanyName = binding.editSearch.getText().toString().trim();
        } else {
            titleOrDemandCompanyName = binding.editSearch.getText().toString().trim();
        }
        viewModel.getDataList(isAcceptQuote, categoryType, titleOrCompanyName, titleOrDemandCompanyName, type, isLoadMore);
    }

    public void showList(List<PublicMyPriceListEntity> list) {
        if (isLoadMore) {
            binding.rlvView.loadMoreComplete();
            adapter.addDatas(list);
            binding.ivEmpty.setVisibility(View.GONE);
        } else {
            binding.rlvView.refreshComplete();
            adapter.setDatas(list);
            if (list.size() == 0) {
                binding.ivEmpty.setVisibility(View.VISIBLE);
            } else {
                binding.ivEmpty.setVisibility(View.GONE);
            }
        }
    }

//    //中间显示的Toast
//    public void showDelSuccToast(String word) {
//        Toast toast = new Toast(getActivity());
//        View view = LayoutInflater.from(getActivity()).inflate(R.layout.pop_toast_center, null);
//        TextView tvWord = view.findViewById(R.id.tv_word);
//        tvWord.setText(word);
//        toast.setView(view);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
//    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.class_layout:
                if (null != classDatas && classDatas.size() > 0) {
                    showClassPop();
                }
                break;
            case R.id.type_layout:
                if (null != statusDatas && statusDatas.size() > 0) {
                    showTypePop();
                }
                break;
        }
    }

    private void showClassPop() {
        binding.classArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        classPopWindow.showPopwindow(binding.roomLayout, 0, 2);
        classPopWindow.setData(classDatas);
    }

    private void showTypePop() {
        binding.typeArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        typePopWindow.showPopwindow(binding.roomLayout, 0, 2);
        typePopWindow.setData(statusDatas);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseQuedPriceEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MY_PRICE_LIST) {
            loadData(false);
        }
    }


}
